<template>
  <div class="list-wrap">
    <div class="list-head">
      <slot name="search" :searchPage="searchPage"></slot>
    </div>
    <div class="list-inner">
      <div
        class="list-inner-item"
        v-for="(item, index) of renderList"
        :key="item.value"
      >
        <input
          type="checkbox"
          :name="generateId(item.label)"
          :id="generateId(item.value)"
          :data-value="item.value"
          @change="handleChange(item.value)"
        />
        <label :for="generateId(item.value)">
          <slot :row="item" :index="index"></slot>
        </label>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, ref } from "vue";

export default defineComponent({
  props: {
    list: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, ctx) {
    const baseFn = () => () => {
      return true;
    };
    let searchFn = ref(baseFn());
    const renderList = computed(() => {
      return props.list.filter(searchFn.value);
    });
    const uuid = Math.ceil(Math.random() * Math.pow(10, 10)).toString(16);
    const generateId = (s: StrONum) => {
      return `${uuid}_${s}`;
    };
    const selectedList: StrONum[] = [];
    const handleChange = (value: StrONum) => {
      const index = selectedList.findIndex((m) => m == value);
      if (index > -1) selectedList.splice(index, 1);
      else selectedList.push(value);
    };
    const getSelectedList = () => {
      const filterList = renderList.value.map((m: any) => m.value);
      const list = selectedList.filter((v) => filterList.includes(v));
      selectedList.length = 0;
      return list;
    };
    const searchPage = (params: any) => {
      searchFn.value = params.constructor === Function ? params : baseFn();
    };
    return {
      uuid,
      generateId,
      selectedList,
      handleChange,
      getSelectedList,
      searchPage,
      renderList,
    };
  },
});
</script>

<style scoped>
.list-wrap {
  box-sizing: border-box;
  padding: 4px;
  border-radius: 10px;
  height: 100%;
  width: 100%;
  border: 1px solid #000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.list-inner {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>